package flights.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import flights.bi.Airline;
import flights.db.AirlineHandler;

/**
 * Servlet implementation class AirlineServlet
 */
public class AirlineServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String url = request.getPathInfo();
		response.setContentType( "text/html" ); 
		if (url != null && url.indexOf("get") != -1)
		{
			if(url.indexOf("id") !=-1)
			{
				String id = request.getParameter("id");
				Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
				Airline airline = null;
				try {
					airline = AirlineHandler.getAirlineById(id);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (airline != null)
				{
					out.print("{\"status\":1, \"data\":" +gson.toJson(airline) + "}");
				}
				else
				{
					out.print("{\"status\":0, \"data\":" +gson.toJson(airline) + "}");
				}
			}	
			else
			{
				Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
				try
				{
					List<Airline> airlines = AirlineHandler.getAll();
					out.print(gson.toJson(airlines));
				}
				catch (Exception e)
				{
					out.print(e.getMessage());
				}
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		PrintWriter out = response.getWriter();
		String url = request.getPathInfo();
		response.setContentType("text/html"); 
		if (url != null && url.indexOf("update") != -1)
		{
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
			StringBuilder sb = new StringBuilder();
		    BufferedReader br = request.getReader();
		    String str;
		    
		    while( (str = br.readLine()) != null ){
		        sb.append(str);
		    }    
		    
		    if (sb != null && sb.length() > 0 ) {
				Type airlineType = new TypeToken<Airline>(){}.getType();
				Airline airline = gson.fromJson(sb.toString(), airlineType);
				java.util.Date today = new java.util.Date();
				java.sql.Date sqlToday = new java.sql.Date(today.getTime());
				airline.setRegistration_date(sqlToday);
				int nRows;
				try {
					List<Airline> airlines =new ArrayList<Airline>();
					airlines.add(airline);
					nRows = AirlineHandler.upsertAirline(airlines);
					out.write("{\"status\":" + nRows + "}");
				} catch (SQLException e) {
					out.write(e.getMessage());
					e.printStackTrace();
				}
			}
		}
		else if (url != null && url.indexOf("delete") != -1)
		{
			StringBuilder sb = new StringBuilder();
		    BufferedReader br = request.getReader();
		    String str;
		    
		    while( (str = br.readLine()) != null ){
		        sb.append(str);
		    }    
		    
		    
			try
			{
				JSONObject js = new JSONObject(sb.toString());
			    Object id = null;
				id = js.get("aid");
				Airline air = AirlineHandler.delAirlineById(id.toString());
				out.write("{\"status\":" + (air != null ? 1 : 0) + "}");
			}
			catch (NumberFormatException ex)
			{
				out.write(ex.getMessage());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				out.write(e.getMessage());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
